package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Category;
import com.zrrd.reggie.bean.Dish;

import com.zrrd.reggie.bean.DishDto;
import com.zrrd.reggie.bean.DishFlavor;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.CategoryService;
import com.zrrd.reggie.service.DishFlavorService;
import com.zrrd.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        QueryWrapper<Dish> wrapper=new QueryWrapper<>();
        //按表中字段排序
        wrapper.orderByDesc("sort");
        if (name!=null&& !name.equals("")){
            wrapper.like("name",name);
        }
        Page<Dish> pageInfo =new Page<>(page,pageSize);
        dishService.page(pageInfo,wrapper);
        //现在应该返回扩展类！
        //给扩展类传值
        Page<DishDto> pageDto =new Page<>();

        //一个工具类帮助复制对象，必须有相同字段
        //第一个是要传过去的，第二个是要收到的，第三个里获取什么
        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        List<Dish> dishList = pageInfo.getRecords();
        //
        List<DishDto> dtoList =new ArrayList<>();
        for(Dish dish:dishList){
            DishDto dto =new DishDto();
            //使用对象拷贝
            BeanUtils.copyProperties(dish,dto);
            Category byId = categoryService.getById(dish.getCategoryId());
            dto.setCategoryName(byId.getName());
            dtoList.add(dto);
        }
            pageDto.setRecords(dtoList);
        return R.success(pageDto);
    }
    //停售
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status")Integer status, Long[] ids){
        List<Dish> dishList = dishService.listByIds(Arrays.asList(ids));
        for (Dish dish : dishList){
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishList);
        //停售也是修改
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("成功");
    }

    //添加方法
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dto){
        log.info("收到请求"+dto);
        dishService.saveDish(dto);
        //添加完毕后删缓存
        redisTemplate.delete("dish_"+dto.getCategoryId());
        return R.success("添加成功");
    }
    //更新时用于展示
    @GetMapping("/{id}")
    public R<DishDto> updateById(@PathVariable("id") Long id){
        //获取菜品
        Dish dish = dishService.getById(id);
        Category category = categoryService.getById(dish.getCategoryId());
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",id);
        List<DishFlavor> flavorslist = dishFlavorService.list(wrapper);
        DishDto dto=new DishDto();
        BeanUtils.copyProperties(dish,dto);
        dto.setCategoryName(category.getName());
        dto.setFlavors(flavorslist);
        return R.success(dto);
    }
    //真正的修改办法
    //直接删除原来的加入最新的
    @PutMapping
    public R<String> update(@RequestBody DishDto dto){
        dishService.updateDish(dto);
        redisTemplate.delete("dish_"+dto.getCategoryId());
        return R.success("成功");
    }
    @DeleteMapping
    public R<String> delete(Long[] ids){
       dishService.deleteDish(ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId){
        //定义最终的返回集合
        List<DishDto> dtoList = new ArrayList<>();
        String key = "dish_"+categoryId;
        //从redis中获取数据
       dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
       if (dtoList!=null){
           log.info("走缓存中获取数据");
           return R.success(dtoList);
       }
        System.out.println("数据库里找");
       //------------以上是加入redis逻辑部分------------------
       //

        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        //只查可售的
        wrapper.eq("status",1);
        List<Dish> dishList = dishService.list(wrapper);
        dtoList=new ArrayList<>();
        //创建最终返回的dto集合
        //List<DishDto> dtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish,dto);
            QueryWrapper<DishFlavor> flavorQueryWrapper = new QueryWrapper<>();
            flavorQueryWrapper.eq("dish_id",dish.getId());
            List<DishFlavor> flavors =dishFlavorService.list(flavorQueryWrapper);
            dto.setFlavors(flavors);
            dtoList.add(dto);
        }
        //返回前将结果存入
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);


        return R.success(dtoList);
    }
}
